package com.example.demo.service.lmp;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.mapper.ChatMapper;
import com.example.demo.model.ChatHistory;
import com.example.demo.service.IChatHistoryService;
import com.example.demo.vo.PageVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
/*
聊天历史记录
 */
@Service
public class ChatHistoryServicelmp implements IChatHistoryService {
    @Autowired
    private ChatMapper chatMapper;


    @Override
    public ChatHistory add(ChatHistory chatHistory) {

        if(chatHistory==null){
            throw new RuntimeException("添加消息不能为空");
        }
        //记录消息时间
        chatHistory.setTime(new Date());
        int hh = chatMapper.insert(chatHistory);
        if(hh >0){
         return chatHistory;
        }
       throw new RuntimeException("插入历史记录失败");
    }

    /*
      *分页查询历史记录列表
     */
    @Override
    public PageVo<ChatHistory> listChatHistory(Integer pageNumber, Integer pageSize) {
        QueryWrapper<ChatHistory> queryWrapper = new QueryWrapper<>();
        // 返回结果按照时间倒序排序
        queryWrapper.orderByDesc("time");
        IPage<ChatHistory> pageParam = new Page<>(pageNumber, pageSize);
        IPage<ChatHistory> chatHistoryIPage = chatMapper.selectPage(pageParam, queryWrapper);

        // 检查 chatHistoryIPage 是否为 null
        if (chatHistoryIPage == null) {
            throw new RuntimeException("查询聊天历史记录失败");
        }

        return new PageVo<>(chatHistoryIPage);
    }
}
